import { app, BrowserWindow, shell, dialog } from 'electron'
import { IPC_CHANNELS } from 'shared/ipcChannels'
import { accountManager } from '#/managers/AccountManager'
import { createLogger } from '#/logger'
import { typedIpcMainHandle } from '#/utils'

function setupIpcHandlers() {
  typedIpcMainHandle(IPC_CHANNELS.chrome.toggleDevTools, event => {
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
      if (win.webContents.isDevToolsOpened()) {
        win.webContents.closeDevTools()
      } else {
        win.webContents.openDevTools()
      }
    }
  })

  typedIpcMainHandle(IPC_CHANNELS.app.openLogFolder, () => {
    shell.openPath(app.getPath('logs'))
  })

  typedIpcMainHandle(IPC_CHANNELS.app.openPath, (_, path: string) => {
    return shell.openPath(path)
  })

  typedIpcMainHandle(IPC_CHANNELS.account.switch, (_, { account }) => {
    accountManager.setAccountName(account.id, account.name)
  })

  // 接收来自渲染进程的日志
  typedIpcMainHandle(IPC_CHANNELS.sendLog, (_, { scope, level, message }) => {
    const logger = createLogger(scope)
    logger[level](message)
  })

  // 文件选择对话框
  typedIpcMainHandle(IPC_CHANNELS.dialog.openFile, async (_, options) => {
    const result = await dialog.showOpenDialog(options)
    return result
  })
}

export function setupAppIpcHandlers() {
  setupIpcHandlers()
}
